<?php

namespace App\Http\Middleware;

use Closure;

class WebAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // echo "string";die;
        $url = config('marketing.ip_url');
        $ip_key = config('marketing.ip_key');
        $ip = request()->getClientIp();
        $ip_content = file_get_contents('ip.txt');
        $ip_arr = explode("\n",$ip_content);
        if(in_array($ip,$ip_arr)){
            return redirect()->away(config('marketing.ip_check'));
        }
        // $ip = '182.250.250.42';
        $ip_check = filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE);
        if($ip_check){
            $url_query = $url . '?key=' . $ip_key . '&ip=' . $ip;
            $ip_address = file_get_contents($url_query);
            $ip_address = explode(';',$ip_address);
            $address = end($ip_address);
            $ip_range = explode(',',config('marketing.ip_range'));
            if(!in_array($address, $ip_range)){
                return redirect()->away(config('marketing.url_redirect'));
            }
        }
        return $next($request);
    }
}
